<template>
  <el-card body-style="width=100%;height=100%">
     <div slot="header" class="clearfix">
      <span>我的资料</span>
    </div> 
      <div class="form">
        <el-form ref="dataForm" :rules="rules"  label-width="80px" :model="info">
          <el-form-item label="id："  prop="id">
            <el-input readonly v-model="info.id"></el-input>
          </el-form-item>
          <el-form-item  prop="username" label="用户名：">
            <el-input v-model="info.username"></el-input>
          </el-form-item>
          <el-form-item  prop="username" label="昵称：">
            <el-input v-model="info.nickName"></el-input>
          </el-form-item>
          <el-form-item prop="oldPassword" label="原密码：">
            <el-input placeholder="不需要更改则此处为空" v-model="info.oldPassword"></el-input>
          </el-form-item>
          <el-form-item prop="password" label="新密码：">
            <el-input placeholder="不需要更改则此处为空" v-model="info.newPassword"></el-input>
          </el-form-item>
          <el-form-item label="头像：" prop="avatar">
            <el-input v-model="info.avatar" v-show="false"></el-input>
            <el-upload class="avatar-uploader" ref="upload" :on-preview="handlePicturePreview"
              :on-change="handleChange" :limit="1" :multiple="true" action="/upload/images" :on-success="handleSuccess"
              :http-request="httpRequest" :auto-upload="false">
              <img v-if="info.avatar" :src="info.avatar" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item class="submit-container">
        <el-button @click="logout" type="info">退出登录</el-button>

            <el-button @click="submitForm" type="primary">更新资料</el-button>
          </el-form-item>
        </el-form>
      </div>
  </el-card>
</template>

<script>
import { getInfo, updateUser, logout } from "@/api/user";
import { getToken, removeToken } from "@/utils/auth";
import { uploadFile } from "@/api/upload";

export default {
  props: {
    user: {
      type: Object,
      default: () => {
        return {
          id: "",
          name: "",
          email: "",
          avatar: "",
          role: "",
          nickName: "",
        };
      },
    },
  },
  data() {
    return {
      info: {
        id: "",
        username: "",
        oldPassword: "",
        newPassword: "",
        avatar: "",
        nickName: "",
      },
      user: {},
      imgChanged: false,
      rules: {
        avatar: [{ required: true, message: "请设置头像", trigger: "blur" }],
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        nickName: [{ required: true, message: "请输入昵称", trigger: "blur" }],
      },
    };
  },
  created() {
    this.getinfo();
  },
  methods: {
    logout() {
      let token = getToken();
      logout(token).then(res => {});
      removeToken();
      this.$message({
        message: "退出登录",
        type: "warning",
      });
      // this.$router.push("/")
    },
    getinfo() {
      let token = getToken();
      console.log("token====>", token);
      getInfo(token).then(res => {
        console.log("获取个人信息res.data===>", res.data);
        if (res.code == 200) {
          this.info.id = res.data.id;
          this.info.username = res.data.username;
          this.info.avatar = res.data.avatar;
          this.info.nickName = res.data.nickName;
        }
      });
    },
    handleUpdate(row) {
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    submitForm() {
      if (
        (this.info.oldPassword != "" && this.info.newPassword == "") ||
        (this.info.oldPassword == "" && this.info.newPassword != "")
      ) {
        return this.$message({
          message: "请输入密码",
          type: "error",
        });
      }
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          if (this.imgChanged) return this.$refs.upload.submit();
          console.log(this.info);
          updateUser(this.info).then(res => {
            this.dialogFormVisible = false;
            if (res.code != 200) {
              return this.$notify({
                title: "失败",
                message: "更新失败" + res.msg,
                type: "error",
                duration: 2000,
              });
            }
            this.$notify({
              title: "成功",
              message: "更新成功",
              type: "success",
              duration: 2000,
            });
          });
        } else {
          this.$message({
            message: "提交失败,有必填项未填",
            type: "error",
          });
          return false;
        }
      });
    },
    resetForm() {
      this.$refs[dataForm].resetFields();
    },
    handleSuccess(response) {
      if (response.code != 200) {
        return this.$message({
          message: "上传失败",
          type: "error",
        });
      }
      if (response && response.data) {
        this.info.avatar = response.data;
        this.$message({
          message: "上传成功",
          type: "success",
        });
      }
    },
    handlePicturePreview(file) {
      this.info.avatar = file.url;
    },
    handleChange(file, fileList) {
      this.imgChanged = true;
      this.info.avatar = URL.createObjectURL(file.raw);
    },
    httpRequest(item) {
      //验证图片格式大小信息
      const isJPG =
        item.file.type == "image/jpeg" || item.file.type == "image/png";
      const isLt3M = item.file.size / 1024 / 1024 < 3;
      if (!isJPG) {
        return this.$message({
          showClose: true,
          message: "上传图片只能是 JPG 或 PNG 格式!",
          type: "warning",
        });
      }
      if (!isLt3M) {
        return this.$message({
          showClose: true,
          message: "上传图片大小不能超过 3MB!",
          type: "warning",
        });
      }
      if (isJPG && isLt3M == true) {
        let fd = new FormData();
        fd.append("file", item.file);
        uploadFile(fd).then(res => {
          this.info.avatar = res.data;
          console.log("上传图片,", res);
          this.$notify({
            title: "成功",
            message: "图片上传成功",
            type: "success",
            duration: 2000,
          });
          const infoData = Object.assign({}, this.info);
          console.log(infoData);
          updateUser(infoData).then(() => {
            this.$notify({
              title: "成功",
              message: "更新成功",
              type: "success",
              duration: 2000,
            });
          });
        });
      }
      this.imgChanged = false;
    },
    imgPreview(url) {
      this.imgPreviewUrl[0] = url;
    },
  },
};
</script>

<style lang="scss" scoped>
.usercard {
  width: 400px;
  height: 400px;
}
.box-center {
  margin: 0 auto;
  display: table;
}

.text-muted {
  color: #777;
}

.user-profile {
  .user-name {
    font-weight: bold;
  }

  .box-center {
    padding-top: 10px;
  }

  .user-role {
    padding-top: 10px;
    font-weight: 400;
    font-size: 14px;
  }

  .box-social {
    padding-top: 30px;

    .el-table {
      border-top: 1px solid #dfe6ec;
    }
  }

  .user-follow {
    padding-top: 20px;
  }
}

.user-bio {
  // margin-top: 20px;
  color: #606266;

  span {
    padding-left: 4px;
  }

  .user-bio-section {
    font-size: 14px;
    // padding: 15px 0;

    .user-bio-section-header {
      border-bottom: 1px solid #dfe6ec;
      padding-bottom: 10px;
      margin-bottom: 10px;
      font-weight: bold;
    }
  }
}

.el-card {
  margin: 0 auto;
  // width: 600px;
  // height: 800px;
  // background: red;
}
.form {
  margin-top: 50px;
}

input[type="file"] {
  display: none;
}

.avatar-uploader .el-upload {
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  border: 1px solid #dcdfe6;
  border-radius: 10px;
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 200px;
  height: 208px;
  display: block;
  border-radius: 10px;
}

.submit {
  // margin-left: 50px;
  margin-left: 100px;
  width: 100px;
  height: 40px;
  // font-size: 20px;
}
.myPorfile-container {
  width: 1400px;
  display: flex;
  // background: red;
}
.el-form-item {
  // background: #409eff;
}
.submit-container {
  width: 100%;
  // background: #409eff;
}
</style>
